import 'package:flutter/material.dart';
import 'package:flutter_hsh/fluttergromore/ads/ads_utils.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import '../../fluttergromore/ads/ad_feed_view.dart';
import '../../style/style.dart';
import '../../widgets/my_app_bar.dart';
import 'jilu_add_logic.dart';
import '../jilu/jilu_logic.dart';  // 导入TaskType枚举

/// 添加清单页面
class JiluAddView extends StatefulWidget {
  const JiluAddView({super.key});

  @override
  State<JiluAddView> createState() => _JiluAddViewState();
}

class _JiluAddViewState extends State<JiluAddView> {
  final JiluAddLogic logic = Get.put(JiluAddLogic());
  final TextEditingController _titleController = TextEditingController();
  final TextEditingController _noteController = TextEditingController();

  @override
  void dispose() {
    _titleController.dispose();
    _noteController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.grey[100],
      appBar: const MyAppBar(
        title: '添加清单',
        isBack: true,
      ),
      body: Column(
        children: [
          // 广告区域
          const MyAdFeedView(),
          // 表单区域
          Expanded(
            child: SingleChildScrollView(
              child: Padding(
                padding: EdgeInsets.all(16.r),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    // 任务类型选择
                    _buildTaskTypeSelector(),
                    
                    SizedBox(height: 16.h),
                    
                    // 时间设置区域
                    _buildTimeSettingArea(),
                    
                    SizedBox(height: 16.h),
                    
                    // 标题输入框
                    _buildTitleInput(),
                    
                    SizedBox(height: 16.h),
                    
                    // 备注输入框
                    _buildNoteInput(),
                    
                    SizedBox(height: 24.h),
                  ],
                ),
              ),
            ),
          ),
          
          // 保存按钮
          _buildSaveButton(),
        ],
      ),
    );
  }





  // 时间设置区域 - 拆分成两个独立按钮
  Widget _buildTimeSettingArea() {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Text(
          '时间设置',
          style: TextStyle(
            fontSize: 16.sp,
            fontWeight: FontWeight.bold,
            color: Colors.grey[700],
          ),
        ),
        SizedBox(height: 8.h),
        Row(
          children: [
            // 左侧：选择日期时间按钮
            Expanded(
              child: _buildDateTimeButton(),
            ),
            SizedBox(width: 12.w),
            // 右侧：设置闹钟按钮
            Expanded(
              child: _buildAlarmButton(),
            ),
          ],
        ),
        SizedBox(height: 8.h),
        // 显示当前设置的时间
        Obx(() => _buildTimeDisplay()),
      ],
    );
  }

  // 选择日期时间按钮
  Widget _buildDateTimeButton() {
    return Container(
      height: 50.h,
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.circular(8.r),
        boxShadow: [
          BoxShadow(
            color: Colors.black.withOpacity(0.05),
            blurRadius: 4,
            offset: const Offset(0, 2),
          ),
        ],
      ),
      child: Material(
        color: Colors.transparent,
        child: InkWell(
          borderRadius: BorderRadius.circular(8.r),
          onTap: () => _handleDateTimeTap(context),
          splashColor: const Color(0xFF8FE5B0).withOpacity(0.2),
          highlightColor: const Color(0xFF8FE5B0).withOpacity(0.1),
          child: Padding(
            padding: EdgeInsets.symmetric(horizontal: 16.w),
            child: Row(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                Icon(
                  Icons.calendar_today,
                  color: const Color(0xFF8FE5B0),
                  size: 20.r,
                ),
                SizedBox(width: 8.w),
                Text(
                  '选择时间',
                  style: TextStyle(
                    fontSize: 14.sp,
                    fontWeight: FontWeight.w500,
                    color: Colors.grey[700],
                  ),
                ),
              ],
            ),
          ),
        ),
      ),
    );
  }

  // 设置闹钟按钮
  Widget _buildAlarmButton() {
    return Container(
      height: 50.h,
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.circular(8.r),
        boxShadow: [
          BoxShadow(
            color: Colors.black.withOpacity(0.05),
            blurRadius: 4,
            offset: const Offset(0, 2),
          ),
        ],
      ),
      child: Material(
        color: Colors.transparent,
        child: InkWell(
          borderRadius: BorderRadius.circular(8.r),
          onTap: () => _handleAlarmTap(context),
          splashColor: Colors.orange.withOpacity(0.2),
          highlightColor: Colors.orange.withOpacity(0.1),
          child: Padding(
            padding: EdgeInsets.symmetric(horizontal: 16.w),
            child: Row(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                Obx(() => Icon(
                  logic.hasAlarm.value ? Icons.notifications_active : Icons.notifications,
                  color: logic.hasAlarm.value ? Colors.orange : Colors.grey[600],
                  size: 20.r,
                )),
                SizedBox(width: 8.w),
                Obx(() => Text(
                  logic.hasAlarm.value ? '闹钟开启' : '设置闹钟',
                  style: TextStyle(
                    fontSize: 14.sp,
                    fontWeight: FontWeight.w500,
                    color: logic.hasAlarm.value ? Colors.orange : Colors.grey[700],
                  ),
                )),
              ],
            ),
          ),
        ),
      ),
    );
  }

  // 显示当前时间设置
  Widget _buildTimeDisplay() {
    if (logic.selectedTime.value.isEmpty) {
      return Container(); // 未设置时间时不显示
    }
    
    return Obx(() {
      final taskType = logic.taskType.value;
      final typeColor = taskType == TaskType.todo ? Colors.blue : Colors.orange;
      final typeName = taskType == TaskType.todo ? '待办' : '提醒';
      
      return Container(
        padding: EdgeInsets.symmetric(horizontal: 16.w, vertical: 8.h),
        decoration: BoxDecoration(
          color: typeColor.withOpacity(0.1),
          borderRadius: BorderRadius.circular(8.r),
          border: Border.all(color: typeColor.withOpacity(0.3)),
        ),
        child: Row(
          children: [
            Icon(
              taskType == TaskType.todo ? Icons.check_circle_outline : Icons.notifications_outlined,
              color: typeColor,
              size: 16.r,
            ),
            SizedBox(width: 8.w),
            Expanded(
              child: Text(
                '$typeName时间: ${logic.selectedTime.value}${logic.hasAlarm.value ? ' (闹钟开启)' : ''}',
                style: TextStyle(
                  fontSize: 12.sp,
                  color: typeColor,
                  fontWeight: FontWeight.w500,
                ),
              ),
            ),
          ],
        ),
      );
    });
  }

  // 标题输入框
  Widget _buildTitleInput() {
    return Container(
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.circular(8.r),
      ),
      child: TextField(
        controller: _titleController,
        decoration: InputDecoration(
          hintText: '请输入标题',
          hintStyle: TextStyle(
            fontSize: 16.sp,
            color: Colors.grey[400],
          ),
          contentPadding: EdgeInsets.symmetric(horizontal: 16.w, vertical: 12.h),
          border: InputBorder.none,
        ),
        style: TextStyle(
          fontSize: 16.sp,
        ),
        maxLines: 1,
      ),
    );
  }

  // 备注输入框
  Widget _buildNoteInput() {
    return Container(
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.circular(8.r),
      ),
      child: TextField(
        controller: _noteController,
        decoration: InputDecoration(
          hintText: '请输入备注',
          hintStyle: TextStyle(
            fontSize: 16.sp,
            color: Colors.grey[400],
          ),
          contentPadding: EdgeInsets.all(16.r),
          border: InputBorder.none,
        ),
        style: TextStyle(
          fontSize: 16.sp,
        ),
        maxLines: 5,
        minLines: 3,
      ),
    );
  }
  


  // 构建任务类型选择器
  Widget _buildTaskTypeSelector() {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Text(
          '任务类型',
          style: TextStyle(
            fontSize: 16.sp,
            fontWeight: FontWeight.bold,
            color: Colors.grey[700],
          ),
        ),
        SizedBox(height: 8.h),
        Obx(() {
          final taskType = logic.taskType.value;
          final isTodo = taskType == TaskType.todo;
          
          return Container(
            height: 50.h,
            decoration: BoxDecoration(
              color: Colors.white,
              borderRadius: BorderRadius.circular(8.r),
              boxShadow: [
                BoxShadow(
                  color: Colors.black.withOpacity(0.05),
                  blurRadius: 4,
                  offset: const Offset(0, 2),
                ),
              ],
            ),
            child: Material(
              color: Colors.transparent,
              child: InkWell(
                borderRadius: BorderRadius.circular(8.r),
                onTap: logic.toggleTaskType,
                child: Padding(
                  padding: EdgeInsets.symmetric(horizontal: 16.w),
                  child: Row(
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    children: [
                      Row(
                        children: [
                          Container(
                            width: 32.r,
                            height: 32.r,
                            decoration: BoxDecoration(
                              shape: BoxShape.circle,
                              color: isTodo ? Colors.blue.withOpacity(0.1) : Colors.orange.withOpacity(0.1),
                              border: Border.all(
                                color: isTodo ? Colors.blue : Colors.orange,
                                width: 2,
                              ),
                            ),
                            child: Icon(
                              isTodo ? Icons.check_circle_outline : Icons.notifications_outlined,
                              color: isTodo ? Colors.blue : Colors.orange,
                              size: 18.r,
                            ),
                          ),
                          SizedBox(width: 12.w),
                          Column(
                            mainAxisAlignment: MainAxisAlignment.center,
                            crossAxisAlignment: CrossAxisAlignment.start,
                            children: [
                              Text(
                                isTodo ? '待办事项' : '提醒事项',
                                style: TextStyle(
                                  fontSize: 14.sp,
                                  fontWeight: FontWeight.w600,
                                  color: Colors.grey[800],
                                ),
                              ),
                              Text(
                                isTodo ? '需要完成的任务' : '需要提醒的事项',
                                style: TextStyle(
                                  fontSize: 12.sp,
                                  color: Colors.grey[500],
                                ),
                              ),
                            ],
                          ),
                        ],
                      ),
                      Icon(
                        Icons.swap_horiz,
                        color: Colors.grey[400],
                        size: 20.r,
                      ),
                    ],
                  ),
                ),
              ),
            ),
          );
        }),
      ],
    );
  }

  // 保存按钮
  Widget _buildSaveButton() {
    return Container(
      width: double.infinity,
      padding: EdgeInsets.all(16.r),
      child: ElevatedButton(
        onPressed: () {
          AdsUtils.showRewardVideoAd();
          // 保存任务
          logic.saveTask(_titleController.text, _noteController.text);
        },
        style: ElevatedButton.styleFrom(
          backgroundColor: kAppThemeColor,
          padding: EdgeInsets.symmetric(vertical: 12.h),
          shape: RoundedRectangleBorder(
            borderRadius: BorderRadius.circular(8.r),
          ),
        ),
        child: Text(
          '保存',
          style: TextStyle(
            fontSize: 16.sp,
            fontWeight: FontWeight.bold,
            color: Colors.white,
          ),
        ),
      ),
    );
  }

  // 处理日期时间按钮点击
  void _handleDateTimeTap(BuildContext context) {
    logic.showDateTimePicker(context);
  }

  // 处理闹钟按钮点击
  void _handleAlarmTap(BuildContext context) {
    if (logic.selectedTime.value.isEmpty) {
      // 未设置时间，先提示设置时间
      showDialog(
        context: context,
        builder: (context) => AlertDialog(
          title: const Text('提示'),
          content: const Text('请先设置提醒时间，然后才能开启闹钟功能'),
          actions: [
            TextButton(
              onPressed: () => Navigator.pop(context),
              child: const Text('确定'),
            ),
          ],
        ),
      );
    } else {
      // 已设置时间，显示闹钟设置界面
      _showAlarmSettings(context);
    }
  }



  // 显示闹钟设置界面
  void _showAlarmSettings(BuildContext context) {
    showDialog(
      context: context,
      builder: (context) => StatefulBuilder(
        builder: (context, setState) {
          return AlertDialog(
            title: const Text('闹钟设置'),
            content: Column(
              mainAxisSize: MainAxisSize.min,
              children: [
                Row(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  children: [
                    const Text('开启闹钟提醒'),
                    Switch(
                      value: logic.hasAlarm.value,
                      onChanged: (value) {
                        setState(() {
                          logic.hasAlarm.value = value;
                        });
                      },
                    ),
                  ],
                ),
                if (logic.hasAlarm.value) ...[
                  SizedBox(height: 16.h),
                  Text(
                    '闹钟将在 ${logic.selectedTime.value} 提醒您',
                    style: TextStyle(
                      fontSize: 12.sp,
                      color: Colors.green,
                    ),
                  ),
                ],
              ],
            ),
            actions: [
              TextButton(
                onPressed: () => Navigator.pop(context),
                child: const Text('确定'),
              ),
            ],
          );
        },
      ),
    );
  }
}